﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;

namespace FlexySys.Common.Extension
{
    public static class Conversion
    {

        #region DataTable

        public static XElement ToXml(this DataTable table)
        {
            if (table == null)
                return null;

            if (table.DataSet != null)
                return table.DataSet.ToXml();
            else
            {
                table.TableName = "Row";
                DataSet ds = new DataSet();
                ds.Tables.Add(table);
                return ds.ToXml();
            }

        }

        public static XElement ToXml(this DataSet ds)
        {
            ds.DataSetName = "Table";
            StringWriter sw = new StringWriter();
            ds.WriteXml(sw, XmlWriteMode.WriteSchema);
            return XElement.Parse(sw.ToString());
        }

        public static DataTable ToDataTable(this XElement xElement)
        {
            DataSet ds = new DataSet();
            ds.ReadXml(new XmlTextReader(new StringReader(xElement.ToString())));

            return ds.Tables[0];
        }

        public static DataTable FieldToDataTable(this XElement xElement)
        {
            return xElement.Element("Value").Element("Table").ToDataTable();
        }

        public static DataTable ToDataTable(this string xml)
        {
            XElement xElement = XElement.Parse(xml);
            return xElement.ToDataTable();
        }

        #endregion


    }
}
